#include "mainwidget.h"
#include "ui_mainwidget.h"

#include "databasemanager.h"
#include <QSqlRelationalTableModel> // 多表操作
#include <QTimer>
mainWidget::mainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mainWidget)
{
    ui->setupUi(this);

    // 初始化设备信息
    this->devInfo();
    b.init();
    this->initModels();

}

mainWidget::~mainWidget()
{
    delete ui;
}


void mainWidget::devInfo()
{
    ui->lineEdit_yunxingshijian_2->setText("0时0分0秒");
    this->runTime();
}

void mainWidget::initModels()
{
    if (!DatabaseManager::getInstance().connectMysql())
    {
        return;
    }
    QSqlRelationalTableModel* serialModel = DatabaseManager::getInstance().getSerialModel();
    serialModel = new QSqlRelationalTableModel(this);

    serialModel->setTable("serialport_config");
    // 通过模型查询数据
    serialModel->select();
    ui->tableView_chuankou_2->setModel(serialModel);
    // 修改表头
    serialModel->setHeaderData(0, Qt::Horizontal, "端口号");
    serialModel->setHeaderData(1, Qt::Horizontal, "串口号");
    serialModel->setHeaderData(2, Qt::Horizontal, "串口名");
    serialModel->setHeaderData(3, Qt::Horizontal, "波特率");
    serialModel->setHeaderData(4, Qt::Horizontal, "数据位");
    serialModel->setHeaderData(5, Qt::Horizontal, "停止位");
    serialModel->setHeaderData(6, Qt::Horizontal, "校验位");
    serialModel->setHeaderData(7, Qt::Horizontal, "流控制");
    serialModel->setHeaderData(8, Qt::Horizontal, "接收空闲时间");
    serialModel->setHeaderData(9, Qt::Horizontal, "发送空闲时间");

    // 设置表格的显示模式
    ui->tableView_chuankou_2->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->tableView_chuankou_2->setAlternatingRowColors(true);
    // 修改模型的提交方式（更新数据表的方式）
    serialModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    QSqlRelationalTableModel *clientModel = new QSqlRelationalTableModel(this);
    clientModel->setTable("users");
    clientModel->select();

    // 关联到第二个tableView
    ui->tableView_yonghu_2->setModel(clientModel);
    ui->tableView_yonghu_2->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->tableView_yonghu_2->setAlternatingRowColors(true);
    clientModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
}

void mainWidget::runTime()
{
    QTimer *time = new QTimer(this);

    connect(time, &QTimer::timeout, [this](){
        static int second = 0;
        second++;
        QString timeStr = QString("%1时%2分%3秒").arg(second / 3600).arg((second % 3600) / 60).arg(second % 60);
        ui->lineEdit_yunxingshijian_2->setText(timeStr);
    });
    time->start(1000);
}
